#include "../include/attendance_handler.h"
#include "../include/db_manager.h"
#include <jsoncpp/json/json.h>
#include <iostream>

std::string AttendanceHandler::getAllAttendance() {
    DBManager& db = DBManager::getInstance();
    
    std::string query = "SELECT * FROM attendance ORDER BY Employee_id, Year DESC, Month DESC";
    auto results = db.executeSelectQuery(query);
    
    Json::Value response;
    response["success"] = true;
    response["data"] = Json::Value(Json::arrayValue);
    
    for (const auto& row : results) {
        Json::Value attendance;
        attendance["employee_id"] = row.at("Employee_id");
        attendance["year"] = row.at("Year");
        attendance["month"] = row.at("Month");
        attendance["attendance_days"] = row.at("Attendance_days");
        attendance["leave_days"] = row.at("Leave_days");
        
        response["data"].append(attendance);
    }
    
    Json::FastWriter writer;
    return writer.write(response);
}

std::string AttendanceHandler::getAttendanceById(const std::string& id) {
    // 考勤表使用复合主键，这里简化处理
    return getAllAttendance();
}

std::string AttendanceHandler::addAttendance(const std::string& data) {
    Json::Value request_data;
    Json::Reader reader;
    
    if (!reader.parse(data, request_data)) {
        Json::Value response;
        response["success"] = false;
        response["message"] = "数据格式错误";
        Json::FastWriter writer;
        return writer.write(response);
    }
    
    DBManager& db = DBManager::getInstance();
    
    std::string query = std::string("INSERT INTO attendance (Employee_id, Year, Month, Attendance_days, Leave_days) VALUES ('") +
                       db.escapeString(request_data["employee_id"].asString()) + "', " +
                       request_data["year"].asString() + ", " +
                       request_data["month"].asString() + ", " +
                       request_data["attendance_days"].asString() + ", " +
                       request_data["leave_days"].asString() + ")";
    
    Json::Value response;
    if (db.executeQuery(query)) {
        response["success"] = true;
        response["message"] = "考勤记录添加成功";
    } else {
        response["success"] = false;
        response["message"] = "考勤记录添加失败";
    }
    
    Json::FastWriter writer;
    return writer.write(response);
}

std::string AttendanceHandler::updateAttendance(const std::string& id, const std::string& data) {
    // 解析复合主键：格式为 "employee_id:year:month"
    size_t pos1 = id.find(':');
    size_t pos2 = id.find(':', pos1 + 1);
    
    if (pos1 == std::string::npos || pos2 == std::string::npos) {
        Json::Value response;
        response["success"] = false;
        response["message"] = "无效的考勤记录ID格式";
        Json::FastWriter writer;
        return writer.write(response);
    }
    
    std::string employee_id = id.substr(0, pos1);
    std::string year = id.substr(pos1 + 1, pos2 - pos1 - 1);
    std::string month = id.substr(pos2 + 1);
    
    Json::Value request_data;
    Json::Reader reader;
    
    if (!reader.parse(data, request_data)) {
        Json::Value response;
        response["success"] = false;
        response["message"] = "数据格式错误";
        Json::FastWriter writer;
        return writer.write(response);
    }
    
    DBManager& db = DBManager::getInstance();
    
    std::string query = std::string("UPDATE attendance SET ") +
                       "Attendance_days = " + request_data["attendance_days"].asString() + ", " +
                       "Leave_days = " + request_data["leave_days"].asString() + " " +
                       "WHERE Employee_id = '" + db.escapeString(employee_id) + 
                       "' AND Year = " + year + " AND Month = " + month;
    
    Json::Value response;
    if (db.executeQuery(query)) {
        response["success"] = true;
        response["message"] = "考勤记录更新成功";
    } else {
        response["success"] = false;
        response["message"] = "考勤记录更新失败";
    }
    
    Json::FastWriter writer;
    return writer.write(response);
}

std::string AttendanceHandler::deleteAttendance(const std::string& id) {
    // 解析复合主键：格式为 "employee_id:year:month"
    size_t pos1 = id.find(':');
    size_t pos2 = id.find(':', pos1 + 1);
    
    if (pos1 == std::string::npos || pos2 == std::string::npos) {
        Json::Value response;
        response["success"] = false;
        response["message"] = "无效的考勤记录ID格式";
        Json::FastWriter writer;
        return writer.write(response);
    }
    
    std::string employee_id = id.substr(0, pos1);
    std::string year = id.substr(pos1 + 1, pos2 - pos1 - 1);
    std::string month = id.substr(pos2 + 1);
    
    DBManager& db = DBManager::getInstance();
    
    std::string query = "DELETE FROM attendance WHERE Employee_id = '" + db.escapeString(employee_id) + 
                       "' AND Year = " + year + " AND Month = " + month;
    
    Json::Value response;
    if (db.executeQuery(query)) {
        response["success"] = true;
        response["message"] = "考勤记录删除成功";
    } else {
        response["success"] = false;
        response["message"] = "考勤记录删除失败";
    }
    
    Json::FastWriter writer;
    return writer.write(response);
}

std::string AttendanceHandler::getAttendanceStatistics() {
    DBManager& db = DBManager::getInstance();
    
    auto results = db.executeSelectQuery("SELECT COUNT(*) as total FROM attendance");
    int total_records = results.empty() ? 0 : std::stoi(results[0].at("total"));
    
    Json::Value response;
    response["success"] = true;
    response["total_records"] = total_records;
    
    Json::FastWriter writer;
    return writer.write(response);
}

std::string AttendanceHandler::getAttendanceByEmployee(const std::string& employee_id) {
    DBManager& db = DBManager::getInstance();
    
    std::string query = "SELECT * FROM attendance WHERE Employee_id = '" + db.escapeString(employee_id) + "' ORDER BY Year DESC, Month DESC";
    auto results = db.executeSelectQuery(query);
    
    Json::Value response;
    response["success"] = true;
    response["data"] = Json::Value(Json::arrayValue);
    
    for (const auto& row : results) {
        Json::Value attendance;
        attendance["employee_id"] = row.at("Employee_id");
        attendance["year"] = row.at("Year");
        attendance["month"] = row.at("Month");
        attendance["attendance_days"] = row.at("Attendance_days");
        attendance["leave_days"] = row.at("Leave_days");
        
        response["data"].append(attendance);
    }
    
    Json::FastWriter writer;
    return writer.write(response);
} 